# Base version:
#   https://blog.csdn.net/weixin_39347873/article/details/143921129
# 20250801 
#    + 添加城市接口
#    * 增加更多的输出项目：
#           2025-08-01 郑州，天气:晴，温度:[36 ,28], [日出 05:35，日落 19:28]
#      原始输出：
#           今天是：2025-08-01，天气:晴，温度:36°C
#

from datetime import datetime
import requests
from bs4 import BeautifulSoup
import re


citys= {
    "郑州":"101180101",
    "西宁":"101150101"
}

def clear_number_of_string(rhs_in_str):
    match = re.search(r'-?\d+(?:\.\d+)?', rhs_in_str)
    if match:
        ret = match.group()
    return ret


def get_weather(city_name):
    city_code = citys[city_name]
    
    if city_code is None:
        # 目标URL，这里我选择青海西宁
        url = 'https://www.weather.com.cn/weather1d/101150101.shtml'
    else:
        url = f'https://www.weather.com.cn/weather1d/{city_code}.shtml'
    try:
        response = requests.get(url)
        response.encoding = 'utf-8'
        response.raise_for_status()

        # 解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')

        # 提取天气预报信息，这里需要根据实际页面结构来定位元素
        # 假设天气预报信息在一个id为"7d"的div标签内
        forecast_div = soup.find('div', id='today')

        # 检查是否找到了forecast_div
        if forecast_div is not None:
            # 继续解析forecast_div中的内容，这里需要根据实际结构来编写
            # 假设每天的天气预报在一个class为"t clearfix"的div标签内
            daily_forecasts = forecast_div.find_all('div', class_='t')

            # 打印每天的天气预报信息
            for daily_forecast in daily_forecasts:
                data = get_today_date()  # 获取日期
                weather = daily_forecast.find('p', class_='wea').text  # 获取天气状况
                
                #temperature = daily_forecast.find_all('p', class_='tem').text.strip()  # 获取温度
                tem_tag = daily_forecast.find('p', class_='tem')
                if tem_tag:
                    high_temp = tem_tag.find('span').text if tem_tag.find('span') else "N/A"  # 最高温
                    low_temp = tem_tag.find_next('p', class_='tem').text.strip()
                    high_temp = clear_number_of_string(high_temp) 
                    low_temp = clear_number_of_string(low_temp)
                else:
                    high_temp = low_temp = "N/A"
                
                sun_up = daily_forecast.find('p', class_='sun sunUp').text.strip()  # 获取日落时间
                sun_down = daily_forecast.find('p', class_='sun sunDown').text.strip()  # 获取日落时间
                print(f'{data} {city_name}'+f'，天气:{weather}'+ f'，温度:[{high_temp} ,{low_temp}], [{sun_up}，{sun_down}]')
        else:
            print("暂未获取到今日天气预报信息。")
    except Exception as e:
        print(f"解析网页时发生错误：{e}")

def get_today_date():
    return datetime.now().strftime("%Y-%m-%d")  # 返回当前日期

get_weather("郑州")